package com.gx.auth.dao;

import com.gx.auth.common.BaseDAO;
import com.gx.auth.entity.RoleFunction;
import com.gx.auth.entity.UserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by Administrator on 2017/4/4.
 */
@Slf4j
public class UserRoleDAO extends BaseDAO {
    private class UserRoleMapper implements RowMapper {
        @Override
        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            UserRole userRole = new UserRole();
            userRole.setId(resultSet.getLong("id"));
            userRole.setRoleId(resultSet.getLong("role_id"));
            userRole.setUserId(resultSet.getLong("user_id"));
            return userRole;
        }
    }


    /**
     * 分页查询用户角色关系
     * @param page
     * @param size
     * @return
     */
    public List<UserRole> selectUserRols(int page ,int size) {
        String sql = "select * from auth_user_role limit ?,? ";
        return  jdbcTemplate.query(sql, new Object[]{(page-1)*size,size}, new UserRoleMapper());
    }

    /**
     * 根据ID查询用户角色关系
     * @param id
     * @return
     */
    public RoleFunction selectUserRoleById(Long id) {
        String sql = "select * from auth_user_role where id = ? ";
        return (RoleFunction) jdbcTemplate.queryForObject(sql, new Object[]{id}, new UserRoleMapper());
    }

    /**
     * 根据用户ID查询用户角色对应关系
     * @param userId
     * @return
     */
    public List<UserRole> selectUserRoleByUserId(Long userId) {
        String sql = "select * from auth_user_role where user_id = ? ";
        return  jdbcTemplate.query(sql, new Object[]{userId}, new UserRoleMapper());
    }


    /**
     * 保存用户角色对应关系
     * @param userRole
     */
    public void insertUserRole(UserRole userRole) {
        String sql = "insert  auth_user_role (id,role_id,user_id) values(?,?,?) ";
        jdbcTemplate.update(sql, userRole.getId(),userRole.getRoleId(),userRole.getUserId());
    }

    /**
     * 保存用户角色对用关系集合（一个用户多个角色所以多选）
     * @param userRoles
     */
    public void insertUserRoles(Collection<UserRole> userRoles) {
        String sql = "insert  auth_user_role (role_id,user_id) values(?,?) ";
        List<Object[]> bathargs = new ArrayList<>();
        userRoles.forEach((ur) ->{
            Object [] objects =  new Object[2];
            objects[0] = ur.getUserId();
            objects[1] = ur.getRoleId();
            bathargs.add(objects);
        });
        jdbcTemplate.batchUpdate(sql,bathargs);
    }

    /**
     * 根据id删除角色
     * @param roleId
     * @return
     */
    public int deleteByRoleId(Long roleId) {
        String sql = "delete from auth_role_function where role_id = ? ";
        return jdbcTemplate.update(sql, roleId);

    }

}
